package org.xxpay.pay.channel.jeepay;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.util.JeepayKit;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;
import org.xxpay.pay.util.MyHttp;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: xxpay
 */
@Service
public class JeepayPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(JeepayPayNotifyService.class);
    private static final String logPrefix = "【处理"+JeepayConfig.CHANNEL_NAME+"支付回调】";

    @Override
    public String getChannelName() {
        return JeepayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {

        _log.info("====== 开始处理"+JeepayConfig.CHANNEL_NAME+"支付回调通知 ======");
        HttpServletRequest req = (HttpServletRequest) notifyData;
        JSONObject retObj = new JSONObject();
        JSONObject paramMap = MyHttp.getParam(req);
        _log.info("{}通知参数：{}", logPrefix, paramMap);
        PayOrder payOrder = verifyAliPayParams(paramMap);
        if( payOrder == null ) { //验证参数失败
            retObj.put(PayConstant.RESPONSE_RESULT, PayConstant.RETURN_ALIPAY_VALUE_FAIL);
            return retObj;
        }

        //订单已经支付完成
        if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
            retObj.put(PayConstant.RESPONSE_RESULT, PayConstant.RETURN_ALIPAY_VALUE_SUCCESS);
            return retObj;
        }

        //上游通知 状态

        String channelOrderNo = paramMap.getString("payOrderId"); //上游订单号
        int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId(), channelOrderNo, null);
        if (updatePayOrderRows != 1) {
            _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
            return retObj;
        }
        _log.error("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
        payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);

        // 业务系统后端通知
        baseNotify4MchPay.doNotify(payOrder, true);

        retObj.put(PayConstant.RESPONSE_RESULT, PayConstant.RETURN_ALIPAY_VALUE_SUCCESS);
        return  retObj;
    }

    /**
     * 验证通知参数
     * @return
     */
    private PayOrder verifyAliPayParams(JSONObject paramMap) {
        String payOrderId = paramMap.getString("mchOrderNo");
        String amount = paramMap.getString("amount");
        /*
        * 支付订单状态
            0-订单生成
            1-支付中
            2-支付成功
            3-支付失败
            4-已撤销
            5-已退款
            6-订单关闭
        * */
        String state = paramMap.getString("state");
        if(!"2".equals(state)) {
            _log.error("{}订单非成功状态,payOrderId={}, state={}", logPrefix, payOrderId, state);
            return null;
        }

        PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
        if(payOrder == null){
            _log.error("{}订单不存在,payOrderId={}", logPrefix, payOrderId);
            return null;
        }

        Long amountL = Long.parseLong(amount);
        if(!amountL.equals(payOrder.getAmount())){
            _log.error("{}订单金额验证失败， myselfAmount={}, amount={}", logPrefix, payOrder.getAmount(), amount);
            return null;
        }

        String sign = paramMap.getString("sign");
        JeepayConfig jeepayConfig = new JeepayConfig(getPayParam(payOrder));
        paramMap.remove("sign");
        String checkSign = JeepayKit.getSign(paramMap, jeepayConfig.getAppKey());
        if(!checkSign.equals(sign)) {
            _log.error("{}验签失败", logPrefix);
            return null;
        }

        return payOrder;
    }
}
